import { useState } from 'react'
import { Button, Form, Input, message } from 'antd'
import { useNavigate } from 'react-router-dom'
import { HOME_URL } from '@/router/config'
import { useTranslation } from 'react-i18next'
import { CloseCircleOutlined, LockOutlined, UserOutlined } from '@ant-design/icons'
import LoginByPasswordRequest from '@/core/oauth2/types/model/request/LoginByPasswordRequest'
import controllerUtils from '@/core/utils/controllerUtils'
import authService from '@/core/auth/service/authService'
import globalConfig from '@/core/framework/config/globalConfig'
import CaptchaImageFormItem from '@/ui/antd/pages/login/components/CaptchaImageFormItem'

const LoginForm = (props: any) => {
	const { t } = useTranslation()
	const navigate = useNavigate()
	const [form] = Form.useForm()
	const [loading, setLoading] = useState<boolean>(false)
	const accountPlaceholder = globalConfig.mock ? '用户名：admin / user' : '用户名：'
	const passwordPlaceholder = globalConfig.mock ? '密码：admin / user' : '密码：'
	const accountValue = globalConfig.mock ? 'admin' : ''
	const passwordValue = globalConfig.mock ? 'admin' : ''

	// 登录
	const onFinish = async (loginForm: LoginByPasswordRequest) => {
		await controllerUtils
			.of(async () => {
				setLoading(true)
				await authService.loginByUsernameAndPassword(loginForm)
				message.success('登录成功！')
				navigate(HOME_URL)
				//setTabsList([])
			})
			.finally(() => {
				setLoading(false)
			})
			.doWithDefault()
	}

	const onFinishFailed = (errorInfo: any) => {
		console.log('Failed:', errorInfo)
	}

	return (
		<Form
			form={form}
			name="basic"
			labelCol={{ span: 5 }}
			initialValues={{ remember: true }}
			onFinish={onFinish}
			onFinishFailed={onFinishFailed}
			size="large"
			autoComplete="off"
		>
			<Form.Item name="username" initialValue={accountValue} rules={[{ required: true, message: '请输入用户名' }]}>
				<Input placeholder={accountPlaceholder} prefix={<UserOutlined />} />
			</Form.Item>
			<Form.Item name="password" initialValue={passwordValue} rules={[{ required: true, message: '请输入密码' }]}>
				<Input.Password autoComplete="new-password" placeholder={passwordPlaceholder} prefix={<LockOutlined />} />
			</Form.Item>
			<CaptchaImageFormItem />
			<Form.Item className="login-btn">
				<Button
					onClick={() => {
						form.resetFields()
					}}
					icon={<CloseCircleOutlined />}
				>
					{t('login.reset')}
				</Button>
				<Button type="primary" htmlType="submit" loading={loading} icon={<UserOutlined />}>
					{t('login.confirm')}
				</Button>
			</Form.Item>
		</Form>
	)
}

export default LoginForm
